<template>
  <div class="selectfood">
    <div class="title">添加食物戳我脸决定吃啥</div>
    <div class="btn" @click="select"></div>
    <van-icon name="arrow-left" @click="back" class="font" />
    <div class="body">
      <van-field v-model="food" label="名称" placeholder="请添加食物" @blur="addFood" />
      <van-tag :show="show" closeable size="large" type="primary" @close="close(food)" v-for="(food, i) in foodList" :key="food"
        class="food">
        {{ food }}
      </van-tag>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from "vue";
import { useRouter } from 'vue-router'
import { findFoot, saveFoot, deleteFoot } from "../api/user"
onMounted(() => {
  token.value  = sessionStorage.getItem("token")
  getFoodList() 
})

const router = useRouter()
let foodList = ref([]);
let food = ref("");
let token = ref("")
async function getFoodList() {
  let res = await findFoot(token.value)
  let foodArr = []
  res.data.data.forEach(element => {
    foodArr.push(element.foot)
  });  
  foodList.value = foodArr
}
function back() {
  router.push("/");
}
async function addFood() {
  if (food.value.trim() == "") return;
  await saveFoot(food.value,token.value)
  let result = foodList.value.find((item) => item == food.value);
  if (!result) foodList.value.push(food.value);
  food.value = "";
}
async function close(i) {
  await deleteFoot(i,token.value)
  getFoodList()
}
function select() {
  if (foodList.value.length < 1) return
  let n = Math.floor(Math.random() * foodList.value.length + 1) - 1;
  router.push(`/result/${foodList.value[n]}`);
}
</script>

<style lang="less">
.selectfood {
  width: 100vw;
  height: 100vh;
  background-image: url("../static/background/6.jpg");
  background-size: cover;
  padding: 0.30rem;
  position: relative;

  .title {
    position: absolute;
    right: 0.30rem;
    top: 1rem;
    color: #fff;
    font-weight: 700;
    width: 0.65rem;
    font-size: 0.18rem;
  }

  .btn {
    width: 0.40rem;
    height: 0.40rem;
    position: absolute;
    top: 1.08rem;
    left: 1.65rem;
  }

  .font {
    font-size: 0.30rem;
    color: #fff;
  }

  .food {
    margin: 0.05rem 0.03rem;
  }

  .body {
    margin-top: 2.90rem;
  }
}
</style>